package eval

import (
	"github.com/Knetic/govaluate"
	"golang.org/x/net/html"
)

type DataStruct struct {
}

func (receive *DataStruct) Data(arguments ...interface{}) (interface{}, error) {

	node := arguments[0].(*html.Node)
	return node.Data, nil
}

func (receive *DataStruct) Attr(arguments ...interface{}) (interface{}, error) {

	node := arguments[0].(*html.Node)
	key := arguments[1].(string)
	for _, v := range node.Attr {
		if v.Key == key {
			return v.Val, nil
		}
	}
	return "", nil
}

var dataStruct DataStruct

func NewEval(eval string) (*govaluate.EvaluableExpression, error) {
	m := map[string]govaluate.ExpressionFunction{}

	m["Data"] = dataStruct.Data
	m["Attr"] = dataStruct.Attr
	return govaluate.NewEvaluableExpressionWithFunctions(eval, m)
}
